package wo.jpa.mybatis.generator;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import wo.common.util.WoClassUtil;
import wo.common.util.WoUtil;
import wo.common.util.WoVelocityUtil;
import wo.jpa.reader.entity.WoJPAEntity;

public class MyBatisSQLCreator {
	private final static Logger LOG = LogManager.getLogger(MyBatisSQLCreator.class);
	
	public static void createDaoCode (String rootDir, String entityClass) {
		rootDir = WoUtil.getDirEndWithFileSeparator(rootDir);
		LOG.info("rootDir:" + rootDir + ",entityClass:" + entityClass);
		WoJPAEntity e = new WoJPAEntity(entityClass);
		String fileDir = rootDir + e.getDaoPackage().replace(".", "/") + "/";
		File dir = new File(fileDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("entity", e);
		String filePath = fileDir + e.getDaoInterfaceName() + ".java";
		WoVelocityUtil.mergeToFile("dao.java.vm", filePath, map);
		
		String filePath2 = fileDir + e.getEntityName() + "Provider.java";
		WoVelocityUtil.mergeToFile("sql.provider.vm", filePath2, map);
	}
	
	/**
	 * @param rootDir
	 * @param pkgToScan
	 */
	public static void createDaoCodeByPackage (String rootDir, String pkgToScan) {
        List<Class> classes = WoClassUtil.findClassesByPackage("./", pkgToScan);
        //这个时候我们已经得到了指定包下所有的类的绝对路径了。我们现在利用这些绝对路径和java的反射机制得到他们的类对象
        for (Class s : classes) {
            if (s.getDeclaredAnnotation(Entity.class) != null) {
            	createDaoCode (rootDir, s.getName());
            }
        }
    }

	public static void main (String[] args) throws Exception {
		createDaoCodeByPackage("./src/main/java/", "com.qfedu.psys.po");
		// createDaoCode ("./src/main/java/", "wo.sys.entity.Message");
		// LOG.info(WoVelocityUtil.parse("#set( $e = \"$\" ) ${e}.post();", new HashMap<String, Object>()));
		// LOG.info(WoVelocityUtil.parse("$.post();", new HashMap<String, Object>()));
	}
}
